#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import cgi
import wsgiref.handlers
import os
import sys
import datetime

sys.path.append("./feedparser")

from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.api.urlfetch import InvalidURLError
from google.appengine.ext.db import *

import feedparser
from model import *
from view import *

MENU=u"""
<div>
    <span><a href="home?rssId=%(rssId)s&view=default">Home</a></span> 
    <span><a href="newUrl">Ajoût d'un flux</a></span>
    <span><a href="home?rssId=%(rssId)s&view=image">Vue image</a></span>
</div>
"""

NB_ELT_PAR_PAGE=12

def getNavigator(nbPages=0, currentPage=0, viewdata=None):
    navigator = ""
    if viewdata==None:
        rssId=''
        type='default'
    else:
        rssId=viewdata.rssId
        if rssId==None:rssId=''
        type=viewdata.type
    templatePage= "<a href='home?page=%(page)i&rssId="+rssId+'&view='+type+"'>%(page)i</a> "
    for i in range(1,nbPages):
        navigator+=templatePage%{'page':i}
    return navigator

def requestImageView(requestHandler,rss_list,articles,nbpage,comment,viewdata):
    nbArticles = len(articles)
    newArticles=[]
    nbLignes = int(nbArticles/4)
    for i in range(0,nbLignes):
        j=i*4
        endPos=j+4
        newLine=[]
        while(j<nbArticles and j<endPos):
            newLine.append(articles[j])
            j+=1
        newArticles.append(newLine)
    
    # Id of the selected RSS
    rssId = requestHandler.request.get('rssId')
    # Get the asked page
    page=requestHandler.request.get('page')
    if page:
        page = int(page)
    else :
        page = 1
    offset = NB_ELT_PAR_PAGE*(page-1)
    template_values = {'rss_list':rss_list, 'articles':newArticles, 'menu':MENU%{'rssId':viewdata.rssId},
                       'navigator': getNavigator(nbpage, page, viewdata), 'viewdata':viewdata}
    path = os.path.join(os.path.dirname(__file__), 'html/view_images.html')
    requestHandler.response.headers['Content-Type'] = 'text/html; charset=UTF-8'
    requestHandler.response.out.write(template.render(path, template_values))    